import axios, { AxiosResponse, AxiosRequestConfig ,AxiosInstance} from 'axios';
import {ElLoading,ElMessage} from 'element-plus'
import Crypto from "@/assets/Crypto";



const http = axios.create({
        baseURL: '/',
        timeout: 300 * 1000,
        headers: {'Content-Type': 'application/json; charset=utf-8'}
    }
);
//不需要加载框
const ignoreLoadingList: any = [
    /codeCache\/getProductName/,
    /codeCache\/getRegionByCode/,
    /api\/catastrophe\/isCatastrophe/,
    /api\/antiFraud\/serachAntiFraud/,
    /api\/surevy\/tasks\/searchResponsibilityRatio/
]

//不需要tokenId
const ignoreTokenIdList: any = [
    /api\/login/,
    /forecast\/area/,
    /realtime/,
    /version\/getPublishVersion/
]

//白名单
const whiteList = [
    '/components/'
]

//
const addVariablesList: any = []

let tokenId: any = null
let loadingCount = 0
let loading:any =null
interface Event {
    keyCode: number;
    timestamp: number;
}
const cry:any=new Crypto();
// const loading=ElLoading.service({
//     lock:true,
//     text:'loading',
//     background:'rgba(0,0,0,0.7)'
// })
// Request interceptors
http.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        // do something
        const delTokenId=ignoreTokenIdList.some((url: string | undefined)=>{
            if (typeof url === 'string') {
                return url === config.url
            } else {
                // @ts-ignore
                return url.test(config.url)
            }
        })
        const delLoading=ignoreLoadingList.some((url: string | undefined)=>{
            if (typeof url === 'string') {
                return url === config.url
            } else {
                // @ts-ignore
                return url.test(config.url)
            }
        })
        const addVariables = addVariablesList.some((url: { test: (arg0: any) => any; }) => {
            if (typeof url === 'string') {
                return url === config.url
            } else {
                return url.test(config.url)
            }
        })
        if(!delLoading){
             loading=ElLoading.service({
                lock:true,
                text:'loading',
                background:'rgba(0,0,0,0.7)'
            })
            // loading.close()
            loadingCount++
        }
        if (!delTokenId) {
            tokenId =
                localStorage.getItem('tokenId') != null
                    ? localStorage.getItem('tokenId')
                    : tokenId
            // @ts-ignore
            config.headers.Authorization = tokenId
        }
        if (addVariables) {
            const body = config.data;
            if (!config.data?.variables) {
                config.data = {
                    data: body,
                    variables: {},
                }
            }
        }
        return config;
    },
    (error: string) => {
        Promise.reject(error).then(r => r);
    }
);

// Response interceptors
http.interceptors.response.use(
    async (response: AxiosResponse) => {
        // do something
        // @ts-ignore
        if((localStorage.getItem('safeFlag')&&JSON.parse(localStorage.getItem('safeFlag')))&&typeof response.data==='string'){
          if(!response.data){
              return
          }
          response.data=response.data.replace(/[\r\n]/g,"");
          response.data=cry.decrypt(response.data)
          if(response.data!=null&&response.data!='') {
                response.data=JSON.parse(response.data)
          }
        }
        // @ts-ignore
        if(response.config.url.indexOf('/api/login')> -1 && response.data.success){
            tokenId=response.data.data.tokenId
            localStorage.setItem('tokenId',tokenId)
        }
        const delLoading = ignoreLoadingList.some((url: string | undefined) => {
            if (typeof url === 'string') {
                return url === response.config.url
            } else {
                // @ts-ignore
                return url.test(response.config.url)
            }
        })
        if (!delLoading) {
            loadingCount--
            if (loadingCount == 0) {
                // @ts-ignore
                loading.close()
            }
        }
        const flag=whiteList.some( (url)=>{return url.indexOf(<string>response.config.url)==-1})
        if(!flag){
            ElMessage.error({
                showClose: true,
                message:
                    response.data.msg ||
                    response.data.errMsg ||
                    response.data.errorMessage ||
                    response.data.errorMsg ||
                    response.data.errMessage ||
                    response.data.responseMsg ||
                    '未知错误信息'
            })
        }
        return response.data
    },
    (error: any) => {
        //404等问题可以在这里处理
            ElMessage.error({
                message: '网络或服务器可能出现问题'
            })
         let delLoading = ignoreLoadingList.some((url: string | undefined) => {
            if (typeof url === 'string') {
                return url === error.config.url
            } else {
                    // @ts-ignore
                return url.test(error.config.url)
            }
        })
        if(!delLoading){
            loadingCount--
            if(loadingCount==0){
                // @ts-ignore
                loading.close();
            }
        }
        return Promise.reject(error);
    }
);
//加密情况下f12处理
if(localStorage.getItem('safeFlag')&&JSON.parse(<string>localStorage.getItem('safeFlag'))){
    //屏蔽F12审查元素
    document.onkeydown=()=> {
        // @ts-ignore
        if(window.event.keyCode == 123){    //屏蔽F12
            return false;
            // @ts-ignore
           }else if(window.event.ctrlKey && window.event.shiftKey && window.event.keyCode == 73){    //屏蔽Ctrl+Shift+I，等同于F12
                return false;
            // @ts-ignore
            }else if(window.event.shiftKey && window.event.keyCode == 121){    //屏蔽Shift+F10，等同于鼠标右键
                return false;
        }

    }

    //屏蔽右键菜单
    document.oncontextmenu=(event)=>{
        if(window.event){
            event=<MouseEvent>window.event;
        }try{
            var the=event.srcElement;
            // @ts-ignore
            if(!((the.tagName=="INPUT"&&the.type.toLowerCase()=="text")||the.tagName=="TEXTAREA")){
                return false;
            }
            return true
        }catch(e){
            return false
        }
    }
    // var threshold=160; //打开控制台
    // setInterval(function () {
    //     if(window.outerWidth-window.innerWidth>threshold||window.outerHeight-window.innerHeight>threshold){
    //         //如果打开控制台，则刷新页面
    //         alert('禁用打开调试窗口，请关闭再使用')
    //         window.location.reload();
    //     }
    // },1e3)
}

export default http;
